<?
	function filter_by_value ($array, $index, $value){
        
        if(is_array($array) && count($array)>0) 
        {
            foreach(array_keys($array) as $key){
                $temp[$key] = $array[$key][$index];
                
                if ($temp[$key] == $value){
                    $newarray[$key] = $array[$key];
                }
            }
          }

      return $newarray;
    } 
	
	$interactionF	= "./interactions4.txt";
	$annotationF	= "./annotations3.txt";
	$threshold		= ($_REQUEST['threshold'])?$_REQUEST['threshold']:0.1;
	$tumourp		= $_REQUEST['tumour'];
	$genep			= $_REQUEST['genes'];
	$genesp			= explode('|',$genep);
	
	if (!$iLines = @file($interactionF,FILE_SKIP_EMPTY_LINES)){
		exit;
	}
	
	if (!$aLines = @file($annotationF,FILE_SKIP_EMPTY_LINES)){
		exit;
	}
	
	
	/* Annotations */
	$annotations = array();
	$genes = array();
	$genesInfo = array();
	
	foreach ($aLines as $line_num => $line){
		$annot = explode("\t",$line);
		if ($genep){
		    if (in_array(strtoupper($annot[2]),$genesp) && strtoupper($annot[1])== strtoupper($tumourp)){
				array_push($genesInfo,'<gene><hgnc>'.$annot[3].'</hgnc><ensembl>'.$annot[0].'</ensembl><source>'.$annot[4].'</source></gene>');
			}
			
		}else{
			
			for ($i = 1;$i<=count($annot);$i++){
				if (!array_key_exists($annot[$i],$genes))
					$genes[$annot[$i]] = array();
				if (!in_array($annot[3],$genes[$annot[$i]]))	
					array_push($genes[$annot[$i]],$annot[3]);
			}
		}
	}
	
	if ($genep){
		header("content-type: text/xml");
		echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
		echo '<genes>'."\n";
		foreach ($genesInfo as $g)
			echo $g."\n";
		echo '</genes>'."\n";	
		exit;
	}

	/* Interactions */
	$nodes = array();
	$sharedNodes = array();
	$edges = array();
	foreach ($iLines as $line_num => $line){
		$tmp = explode("\t",$line);

		/* Edges */
		if (!in_array(trim($tmp[0])."-".trim($tmp[1]),$edges)){
			$pv = (float)trim(str_replace(',','.',$tmp[3]));
			if ( $pv < (float) $threshold){
				array_push($edges,array("from" => trim($tmp[0]), "to" => trim($tmp[1]),"pvalue" => $pv ));
				$sharedNodes[trim($tmp[1])]++;
			}	
		}

		/* Nodes */
		if ( $pv < (float) $threshold){
			if (count(filter_by_value($nodes, 'value', trim($tmp[1]) )) <=0){
				$type = "OMIM";
				if (preg_match('/GeneOntology/',$tmp[2]))
					$type = "GO";
				if (preg_match('/Biocarta/',$tmp[2]))
					$type = "BIOCARTA";
				if (preg_match('/Kegg/',$tmp[2]))
					$type = "KEGG";
				if (preg_match('/Interpro/',$tmp[2]))
					$type = "INTERPRO";
				if (preg_match('/Reactome/',$tmp[2]))
					$type = "REACTOME";				
				array_push($nodes,array("type" => $type, "value" => trim($tmp[1]), "genes" => $genes, 'fullname' => trim($tmp[4])));
			}
				
			if (count(filter_by_value($nodes, 'value', trim($tmp[0]))) <=0){
				array_push($nodes,array("type" => "Tumour", "value" => trim($tmp[0]), "genes" => $genes));
			}
		}
	
	}




	header("content-type: text/xml");
	echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".
	'<graphml>'."\n".
	'<key id="d0" for="node" attr.name="id" attr.type="string"></key>'."\n".
	'<key id="d1" for="node" attr.name="type" attr.type="string">'."\n".
		'<default>tumor</default>'."\n".
	'</key>'."\n".
	'<key id="d2" for="node" attr.name="gene" attr.type="string"></key>'."\n".
	'<key id="d3" for="node" attr.name="fullname" attr.type="string"></key>'."\n".
	'<key id="e0" for="edge" attr.name="pvalue" attr.type="string"></key>'."\n".
	'<key id="e1" for="edge" attr.name="shared" attr.type="string"></key>'."\n".
	'<graph id="G" edgedefault="undirected">'."\n";
	
	
	/* Nodes */
	foreach ($nodes as $n){
		echo '<node id="'.$n['value'].'">'."\n";
		echo '<data key="d0">'.$n['value'].'</data>'."\n";
		echo '<data key="d1">'.$n['type'].'</data>'."\n";
		if (count($genes[$n['value']])){
			echo '<data key="d2">'.implode(' ',$genes[$n['value']]).'</data>'."\n";			
		}else{
			echo '<data key="d2"></data>'."\n";		
		}
		echo '<data key="d3">'.$n['fullname'].'</data>'."\n";
		
		echo '</node>'."\n";
	}
	
	/* Edges */
	foreach ($edges as $e){

		echo '<edge id="e'.$j.'" source="'.$e['from'].'" target="'.$e['to'].'">'."\n";
		echo '<data key="e0">'.str_replace(',','.',$e['pvalue']).'</data>'."\n";
		echo '<data key="e1">'.$sharedNodes[$e['to']].'</data>'."\n"; 
		
		echo '</edge>'."\n";

	}
	echo '</graph>'."\n".'</graphml>';

?>